﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace WSServer
{
    public class WSSocketCollection
    {
        static WSSocketCollection instance;
        public static WSSocketCollection collection
        {
            get
            {
                if(instance == null)
                {
                    instance = new WSSocketCollection();
                }
                return instance;
            }
        }

        private List<WSSocket> sockets { get; set; }
        private Timer Swapper { get; set; }
        static object locker = new object();
        public WSSocketCollection()
        {
            sockets = new List<WSSocket>();
            Swapper = new Timer((o) =>
            {
                lock(locker)
                {
                    sockets.RemoveAll(w =>
                        {
                            return w.ShouldBeCleaned();
                        });
                }
            }, null, 60 * 1000, 60 * 1000);
        }

        public WSSocket this[int index]
        {
            get
            {
                return sockets[index];
            }
            set
            {
                sockets[index] = value;
            }
        }
        public void Enqueue(WSSocket socket)
        {
            int index = sockets.FindIndex(s =>
                {
                    return s.identifier == socket.identifier;
                });
            if(index == -1)
            {
                sockets.Add(socket);
            }
            else
            {
                DeleteSocketWithIdentifier(socket.identifier);
                sockets.Add(socket);
            }
        }
        public WSSocket Find(Predicate<WSSocket> predictor)
        {
            return sockets.Find(predictor);
        }
        public void DeleteSocketWithIdentifier(string identifier)
        {
            int index = sockets.FindIndex(s =>
            {
                return s.identifier == identifier;
            });
            if (index != -1)
            {
                try
                {
                    sockets[index].Dispose();
                }
                catch (Exception e)
                { }
                finally
                {
                    sockets.RemoveAt(index);
                }
            }
        }
        public List<WSSocket> allSockets
        {
            get
            {
                return this.sockets;
            }
        }
    }
}
